<template>
    <div>
    <!-- 新增操作 -->
    <el-row type="flex" justify="end" >
        <el-col :span="2">
            <el-button  type="primary" icon="el-icon-edit" @click="saveForm">新增</el-button>
        </el-col>
    </el-row>
    <!-- table数据 -->
    <el-row style="margin-top:20px">
        <el-table 
        :data="tableData"
        border
        height="560"
        style="width: 100%"
        row-key="id"
        default-expand-all
        :tree-props="{children: 'children', hasChildren: 'hasChildren'}">
        <!-- 主键id 暂不需要 -->
        <!-- <el-table-column
        prop="id"
        label="id"
        >
        </el-table-column> -->
        <el-table-column
        prop="sorting"
        label="排序号"
        >
        </el-table-column>
        
        <!-- 有预览效果 图片列 -->
        <el-table-column
            prop="imgId"
            label="图片">
            <template slot-scope="scope">
                <el-image 
                    v-if="scope.row.imgId"
                    :src="`${baseUrl}/image/getImageById/${scope.row.imgId}`"
                    fit="contain"
                    style="width: 100px; height: 100px; cursor: pointer;"
                    @click="handleImagePreview(scope.row.imgId)">
                </el-image>
            </template>
        </el-table-column>
        <!-- 无预览效果 图片列-->
        <!-- <el-table-column
        prop="imgId"
        label="图片"
        >
        <template slot-scope="scope">
            <el-avatar shape="square" :size="100" fit="fill" :src="scope.row.imgId ? `http://localhost:8188/image/getImageById/${scope.row.imgId}` : ''"></el-avatar>
        </template>
        </el-table-column> -->
        <el-table-column
        fixed="right"
        label="操作"
        >
        <template slot-scope="scope">
            <el-button type="success" size="small" @click="openEditWindow(scope.row)">编辑</el-button>
            <el-button type="danger" size="small" @click="confirmDelete(scope.row)" >删除</el-button>
        </template>
        </el-table-column>
        </el-table>
    </el-row>
    <!-- 图片预览的弹窗 -->
    <el-dialog
        v-model="imagePreviewVisible"
        :visible.sync="imagePreviewVisible"
        width="50%"
        :before-close="handleClosePreview">
        <el-image
            style="width: 100%;"
            :src="imagePreviewUrl"
            fit="contain">
        </el-image>
    </el-dialog>
    <!-- 新增弹框 -->
    <el-dialog :title="tile" width="620px"  :visible.sync="imgDialogFormVisible">
        <div class="avatar-container">
        <h1>图片</h1>
        <el-upload
            class="avatar-uploader" 
            action=""
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload">
        <img v-if="imageUrl" :src="imageUrl" class="avatar">
        <div v-else class="avatar-uploader-icon">
            <i class="el-icon-plus"></i>
        </div>
    </el-upload>
        </div>
        <br>
        <br>
    <el-form :model="form" label-width="100px" ref="form"> 
        <el-form-item label="排序号" prop="sorting"  style="display: flex; align-items: center;" >
            <el-input-number v-model="form.sorting" placeholder="排序号" :min="1" :max="1000" :step="1"></el-input-number>
        </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
            <el-button @click="imgDialogFormVisible=false">取 消</el-button>
            <el-button type="primary"  @click="submitForm('form')">确 定</el-button>
        </div>
    </el-dialog>
    </div>
</template>
<script>
import { MessageBox } from 'element-ui';
  export default {
    data() {
        return {
            baseUrl:"http://shuzisan.suguang.cc:8188",
            //baseUrl:"http://127.0.0.1:8188",
            imagePreviewVisible: false, // 控制预览弹窗的显示
            imagePreviewUrl: '', // 当前预览的图片 URL
            tableData:[],//表格数据
            tile:"新增", //弹出框标题
            fd: new FormData(), //创建FormData 对象
            imageUrl:'', //图片路径
            defaultProps: {
            children: 'children',
            label: 'name'
            },
            form: { // 新增对象的表单信息
                sorting:0,
                id:0,
                imgId:0,
            },
            imgDialogFormVisible: false,//控制添加弹出框
        } 
    },
        mounted() {
            this.getImageSortingList(); // 页面加载时自动调用
        },
        methods: {
            handleImagePreview(imgId) {
                this.imagePreviewUrl = this.baseUrl+`/image/getImageById/${imgId}`;
                this.imagePreviewVisible = true; // 打开预览弹窗
            },
            handleClosePreview() {
                this.imagePreviewVisible = false; // 关闭预览弹窗
            },
            openEditWindow(row) { // 打开编辑窗口
                this.tile = "修改信息"
                this.imgDialogFormVisible = true
                this.form.sorting= row.sorting
                this.form.id= row.id
                this.form.imgId= row.imgId
                this.imageUrl = this.baseUrl+"/image/getImageById/"+row.imgId
             },
            // 获取表格数据
            getImageSortingList() { 
                this.$axios.get("imageSorting/getImageSortingList").then(res => {
                if(res.data.flag){
                    this.tableData = res.data.data
                }
                })
            },
            //新增按钮
            saveForm(){
                this.tile = '新增'
                this.imgDialogFormVisible = true
                this.imageUrl = ''
                this.form.sorting = 0
                this.form.id= 0
                this.form.imgId= 0
            },
            handleAvatarSuccess(res, file) {        
            },
            // 图片前置校验
            beforeAvatarUpload(file) {
                const isImage = ['image/jpeg', 'image/png', 'image/gif','image/jpeg'].includes(file.type); // 判断文件类型是否是 jpg, png, gif,jpeg
                const isLt2M = file.size / 1024 / 1024 < 5;
                if (!isImage) {
                    this.$message.error('上传头像图片只能是 JPG, PNG ,JPEG或 GIF 格式!');    
                }
                if (!isLt2M) {
                    this.$message.error('上传头像图片大小不能超过 5MB!')
                }
                this.imageUrl = URL.createObjectURL(file)
                this.fd.set("file",file);
                return true
            },
            // 新增/修改操作
            submitForm(formName) {
                this.$refs[formName].validate((valid) => {
                if (valid) {
                this.fd.set("sorting",this.form.sorting )
                if(this.form.id){
                    this.fd.set("id",this.form.id)
                    this.fd.set("imgId",this.form.imgId)
                // 修改信息
                this.$axios.put('/imageSorting/updateImageSorting',this.fd).then(res => {
                    console.log(res)
                    this.fd.delete("file")
                        if(res.data.flag){
                            this.getImageSortingList();
                            this.$message({
                            type: 'success',
                            message: '修改成功'
                            });
                        this.imgDialogFormVisible = false
                        }else{
                        this.$message({
                        type: 'error',
                        message: '修改失败'
                    
                        });
                    }
                }).catch(err => {
                })
                }else{
                    // 保存信息
                    this.$axios.post('/imageSorting/saveImageSorting',this.fd).then(res => {
                    console.log(res)
                        if(res.data.flag){
                        this.getImageSortingList();
                        this.fd.delete("file")
                        this.$message({
                        type: 'success',
                        message: "保存成功!"
                        
                        });
                        this.imgDialogFormVisible = false
                        }else{
                        this.imgDialogFormVisible = false
                        this.$message({
                        type: 'error',
                        message: '保存失败!'
                        });
                    }
                }).catch(err => {
                })
                }
                } else {
                    console.log('error submit!!');
                    return false;
                }
                });
            },
            resetForm(formName) {
                this.$refs[formName].resetFields();
            },
            // 删除操作
            confirmDelete(row) {
                MessageBox.confirm('确定要删除这条数据吗？', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {
                    // 用户点击了确定按钮，执行删除操作
                    this.$axios.delete("/imageSorting/deleteImageSorting",
                {
                    params:{
                    id:row.id,
                    imgId: row.imgId        
                    }
                }
                ).then(res => {
                    if(res.data.flag){
                    this.getImageSortingList();
                    this.$message({
                    type: 'success',
                    message: '删除成功'
                     });
                    }else{
                        this.$message({
                        type: 'error',
                        message:  '删除失败'
                    });
                }
                })
            })
                .catch(() => {    
            });
            },
    },
  }
</script>
<style>
 .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  .avatar-uploader .el-upload:hover {
    border-color: #409EFF;
  }
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
  }
  .avatar {
    width: 178px;
    height: 178px;
    display: block;
  }
  
</style>